//
//  TTCommentTableController.m
//  Charles
//
//  Created by lanou3g on 16/5/17.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "TTCommentTableController.h"
#import "NetWorkRequestManager.h"
#import "TTCommentModel.h"
#import "TTCommentModelCell.h"
#import "LORefresh.h"
@interface TTCommentTableController ()

@property (nonatomic,strong) NSMutableArray *dataSource1;

@property (nonatomic,strong) NSMutableArray *dataSource2;

@end

@implementation TTCommentTableController

- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = @"评论";
    
    self.dataSource1 = [NSMutableArray array];
    self.dataSource2 = [NSMutableArray array];
    
    
    [self getHotComment];
    [self getNewComment];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TTCommentModelCell" bundle:nil] forCellReuseIdentifier:@"TTCommentModel"];
    
    [self addRefresh];
}

- (void)addRefresh {
    
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.dataSource1 removeAllObjects];
        [weakSelf.dataSource2 removeAllObjects];
        [weakSelf.tableView reloadData];
        
        [weakSelf getHotComment];
        [weakSelf getNewComment];
    }];
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        [weakSelf getNewComment];
        [weakSelf getHotComment];
    }];
}

- (void)getHotComment {
    NSString *hotStr = [NSString stringWithFormat:@"http://comment.api.163.com/api/json/post/list/new/hot/news_gov_bbs/%@/0/10/10/2/2",self.d];
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:hotStr] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *hotArray = jsonDic[@"hotPosts"];
            for (NSDictionary *itemDic in hotArray) {
                NSDictionary *dic = itemDic[@"1"];
                
                TTCommentModel *model = [[TTCommentModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataSource1 addObject:model];
                
            }
            
            for (TTCommentModel *model in self.dataSource1) {
                NSLog(@"%@",model.n);
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
    }];
}

- (void)getNewComment {
    NSString *str = [NSString stringWithFormat:@"http://comment.api.163.com/api/json/post/list/new/normal/news_gov_bbs/%@/desc/40/20/10/2/2",self.d];
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:str] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *hotArray = jsonDic[@"newPosts"];
            for (NSDictionary *itemDic in hotArray) {
                NSDictionary *dic = itemDic[@"1"];
                
                TTCommentModel *model = [[TTCommentModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataSource2 addObject:model];
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    if (section == 0) {
        return self.dataSource1.count;
    } else {
        return self.dataSource2.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TTCommentModelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TTCommentModel" forIndexPath:indexPath];
    
    // Configure the cell...
    
    if (indexPath.section == 0) {
        cell.model = self.dataSource1[indexPath.row];
    } else {
        cell.model = self.dataSource2[indexPath.row];
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 160;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"热门跟帖";
    } else {
        return @"最新跟帖";
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
